<?php

class Zy_prescribe extends CI_Controller {
	function __construct()
	{
		parent::__construct();
		header("Content-type:text/html;charset=utf-8");
	
		$this->load->library('pagination');
		$this->load->helper('form');
		$this->load->helper('url');
		
		$this->load->database();
	}

	function getPages($num)
	{
		$config['base_url'] = base_url().'index.php?c=zy_prescribe&m=indexfrom';
		$config['total_rows'] = $num;
		$config['per_page'] = '10';
		$config['uri_segment'] = 3;
		$config['cur_page'] = $this->uri->segment(3, 0);
		$config['num_links'] = 3;

		$config['first_link'] = '首页';
  	$config['last_link'] = '末页';
  	$config['next_link'] = '下一页>';
  	$config['prev_link'] = '<上一页';
  	
  	$config['page_query_string'] = TRUE;

		$this->pagination->initialize($config);
		
		return $this->pagination;
	}
	
	function index()
	{
		$prescribetable = $this->load->get_var('prescribetable');

		$querystring = "select * from $prescribetable order by convert(name using gb2312)";

		$query = $this->db->query($querystring);
		$num = $query->num_rows();

		if (!$query)
		{
			echo "查询处方失败！";
			return;
		}

		$pagesObj = $this->getPages($num);

		$per = $pagesObj->per_page;
		 
    $cur = $pagesObj->cur_page;
    $cur < 0 ? $cur = 0 : $cur;

    $querystring = "$querystring LIMIT $cur, $per";

		$query = $this->db->query($querystring);
		
		if (!$query)
		{
			echo "查询处方失败！";
			return;
		}
		
		$data['queryresult'] = $query;

		$this->load->view('Zy_view_prescribelist', $data);
	}

	function indexfrom()
	{
		$cur = $this->input->get('per_page');
		
		if (!$cur)
		{
			$cur = 0;
		}
		
		$prescribetable = $this->load->get_var('prescribetable');

		$querystring = "select * from $prescribetable order by convert(name using gb2312)";

		$query = $this->db->query($querystring);
		$num = $query->num_rows();

		if (!$query)
		{
			echo "查询处方失败！";
			return;
		}

		$pagesObj = $this->getPages($num);

		$per = $pagesObj->per_page;

    $querystring = "$querystring LIMIT $cur, $per";

		$query = $this->db->query($querystring);
		
		if (!$query)
		{
			echo "查询处方失败！";
			return;
		}
		
		$data['queryresult'] = $query;

		$this->load->view('Zy_view_prescribelist', $data);
	}
	
	function add()
	{
		$this->load->view('Zy_view_addprescribe');
	}

	function adddone()
	{
		$prescribetable = $this->load->get_var('prescribetable');

		$prescribe_name=$this->input->post('prescribe_name');
		$prescribe_name = Myphplib::trim_space($prescribe_name);

		if (!$prescribe_name || !strcmp($prescribe_name, ""))
		{
			echo "处方名称不能为空!";
			return;	
		}
		
		$prescribe_value=$this->input->post('prescribe_value');

		if (!$prescribe_value || !strcmp($prescribe_value, ""))
		{
			echo "处方内容不能为空!";
			return;	
		}
		
		$prescribe_usemethod=$this->input->post('prescribe_usemethod');

		$prescribe_namestr = $this->db->escape_str($prescribe_name);
		
		$querystring = "select * from $prescribetable where `name`='$prescribe_namestr'";
		$query = $this->db->query($querystring);
		
		if (!$query)
		{
			$url = base_url().'index.php/zy_prescribe/index/0';
			echo "添加处方失败！<a href=$url>回到处方汇总</a>";
			return;
		}

		if ($query->num_rows() != 0)
		{
			$url = base_url().'index.php/zy_prescribe/index/0';
			echo "处方已经存在！<a href=$url>回到处方汇总</a>";
			return;
		}

		$data = array(
			'name' => $prescribe_name,
			'value' => $prescribe_value,
			'usemethod' => $prescribe_usemethod,
			);

		$querystring = $this->db->insert_string($prescribetable, $data);
		
		if (!$this->db->query($querystring))
		{
			$url = base_url().'index.php/zy_prescribe/index/0';
			echo "添加处方失败！<a href=$url>回到处方汇总</a>";
			return;
		}

		$data['title'] = '添加成功！';
		$data['linkstr'] = 'index.php/zy_prescribe/index/0';
		$data['message'] = '回到处方汇总';
		
		$this->load->view('Zy_view_operationresult', $data);
	}
	
	function modify()
	{
		$prescribetable = $this->load->get_var('prescribetable');

		$name = $this->input->get('name');
		$name = Myphplib::trim_space($name);

		$name = $this->db->escape_str($name);

		$querystring = "select * from $prescribetable where $prescribetable.name='$name';";

		$query = $this->db->query($querystring);

		if (!$query)
		{
			$url = base_url().'index.php/zy_prescribe/index/0';
			echo "查找处方失败！<a href=$url>回处方汇总</a>";
			return;
		}
		
		if ($query->num_rows() != 1)
		{
			$url = base_url().'index.php/zy_prescribe/index/0';
			echo "查找处方失败！<a href=$url>回到处方汇总</a>";
			return;
		}

		$data['row'] = $query->row();
		
		$this->load->view('Zy_view_modifyprescribe', $data);
	}

	function modifydone()
	{
		$prescribetable = $this->load->get_var('prescribetable');

		$name = $this->input->get('name');
		$name = Myphplib::trim_space($name);

		$name = $this->db->escape_str($name);

		$prescribe_value=$this->input->post('prescribe_value');
		
		if (!strcmp($prescribe_value, ""))
		{
			echo "处方内容不能为空!";
			return;	
		}

		$prescribe_value = $this->db->escape_str($prescribe_value);
		
		$prescribe_usemethod=$this->input->post('prescribe_usemethod');
		$prescribe_usemethod=$this->db->escape_str($prescribe_usemethod);

		$querystring = "update $prescribetable set `value`='$prescribe_value', `usemethod`='$prescribe_usemethod' where `name`='$name'";
		
		if (!$this->db->query($querystring))
		{
			$url = base_url().'index.php/zy_prescribe/index/0';
			echo "修改处方失败！<a href=$url>回到处方汇总</a>";
			return;
		}

		$this->load->view('Zy_view_modifyprescribesuccess');
	}

	function delete()
	{
		$prescribetable = $this->load->get_var('prescribetable');

		$name = $this->input->get('name');
		$name = Myphplib::trim_space($name);

		$name = $this->db->escape_str($name);

		$querystring = "delete from $prescribetable where $prescribetable.name='$name';";

		$query = $this->db->query($querystring);

		if (!$query)
		{
			$url = base_url().'index.php/zy_prescribe/index/0';
			echo "删除处方失败！<a href=$url>回到处方汇总</a>";
			return;
		}

		$this->load->view('Zy_view_deleteprescribesuccess');
	}

	function search()
	{
		$this->load->view('Zy_view_prescribesearch');
	}
	
	function getSearchPages($num, $search_key, $method)
	{
		$config['base_url'] = base_url().'/index.php?c=zy_prescribe&m='.$method.'&search_key='.$search_key;
		$config['total_rows'] = $num;
		$config['per_page'] = '10';
		$config['uri_segment'] = 3;
		$config['num_links'] = 3;

		$config['first_link'] = '首页';
  	$config['last_link'] = '末页';
  	$config['next_link'] = '下一页>';
  	$config['prev_link'] = '<上一页';

		$config['page_query_string'] = TRUE;

		$this->pagination->initialize($config);
		
		return $this->pagination;
	}
		
	function searchfor($search_key, $method)
	{
		$cur = $this->input->get('per_page');
		
		if (!$cur)
		{
			$cur = 0;
		}

		$prescribetable = $this->load->get_var('prescribetable');

		$search_key_str = $this->db->escape_like_str($search_key);
		
		$querystring = "select * from $prescribetable where name like '%$search_key_str%'";

		$query = $this->db->query($querystring);
		$num = $query->num_rows();

		if (!$query)
		{
			echo "查询处方失败！";
			return;
		}

		$pagesObj = $this->getSearchPages($num, $search_key, $method);

		$per = $pagesObj->per_page;

    $cur < 0 ? $cur = 0 : $cur;

    $querystring = "$querystring LIMIT $cur, $per";

		$query = $this->db->query($querystring);
		
		if (!$query)
		{
			echo "查询处方失败！";
			return;
		}
		
		$data['queryresult'] = $query;
		$data['resultnum'] = $num;

		$this->load->view('Zy_view_prescribesearchresult', $data);
	}

	function dosearch()
	{
		$search_key = $this->input->post('search_key');
		$search_key = Myphplib::trim_space($search_key);
		$this->searchfor($search_key, 'dosearchnext');
	}

	function dosearchnext()
	{
		$search_key = $this->input->get('search_key');
		$search_key = Myphplib::trim_space($search_key);
		$this->searchfor($search_key, 'dosearchnext');
	}
	
	function importprescribe()
	{
		$this->load->view('Zy_view_importprescribe');
	}

	function importprescribe_todb($filename, $encoding)
	{
		$prescribetable = $this->load->get_var('prescribetable');
		
		$gbflag = 0;
		
		if (!strcmp($encoding, 'GB2312'))
		{
			$gbflag = 1;
		}
		
		$file_handle = fopen($filename, "r");
		
		if (!$file_handle)
		{
			return;
		}

		$failflag = 0;
		
		while (!feof($file_handle)) {
			$line = fgets($file_handle);
			$line = trim($line);
			
			if (!strcmp($line, ""))
			{
				continue;
			}
			
			if ($gbflag)
			{
				$line = iconv('GB2312', 'UTF-8', $line);
			} 

			$arr = explode(' ', $line, 2);
			
			$key = $arr[0];
			$value = $arr[1];

			if (!$key || !$value || !strcmp($key, "") || !strcmp($value, ""))
			{
				continue;
			}

			$data = array(
				'name' => $key,
				'value' => $value,
				);
				
			$esckey = $this->db->escape_str($key);

			$querystring = $this->db->insert_string($prescribetable, $data);
			$querystring .= " ON DUPLICATE KEY UPDATE `name`='$esckey'";

			if (!$this->db->query($querystring))
			{
				$failflag = 1;
			}
		}
		
		fclose($file_handle);
		
		return $failflag ? -1 : 0;
	}

	function get_encode($filename)
	{
	   $text = file_get_contents($filename);
	   $first2 = substr($text, 0, 2);
	   $first3 = substr($text, 0, 3);
	   $first4 = substr($text, 0, 3);
	
	   if ($first3 == UTF8_BOM)
	      return 'UTF-8 BOM';
	   elseif ($first4 == UTF32_BIG_ENDIAN_BOM)
	      return 'UTF-32BE';
	   elseif ($first4 == UTF32_LITTLE_ENDIAN_BOM)
	      return 'UTF-32LE';
	   elseif ($first2 == UTF16_BIG_ENDIAN_BOM)
	      return 'UTF-16BE';
	   elseif ($first2 == UTF16_LITTLE_ENDIAN_BOM)
	      return 'UTF-16LE';
	
	   if ($text === iconv('UTF-8', 'UTF-8', iconv('UTF-8', 'UTF-8', $text)))
				return 'UTF-8';
	   if ($text === iconv('UTF-8', 'ASCII', iconv('ASCII', 'UTF-8', $text)))
	      return 'ASCII';
	   if ($text === iconv('UTF-8', 'GB2312', iconv('GB2312', 'UTF-8', $text)))
	      return 'GB2312';
	      
	   return '无法识别';
	}

	function importexceldone($filename) 
	{
		$this->load->library('PHPExcel');
		
		$prescribetable = $this->load->get_var('prescribetable');

		//防止最大可使用的内存总量过少
		if(intval(ini_get('memory_limit')) <= 100)
		{ 
		   ini_set('memory_limit','100M'); 
		}

		$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
		$objPHPExcel = $objReader->load($filename); //$filename可以是上传的文件，或者是指定的文件
		$sheet = $objPHPExcel->getSheet(0);
		$highestRow = $sheet->getHighestRow(); // 取得总行数
		$highestColumn = $sheet->getHighestColumn(); // 取得总列数

		//循环读取excel文件,读取一条,插入一条
		for($j = 1; $j <= $highestRow; $j++)
		{
			$prescribe_name = (string)$objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();

			if (!$prescribe_name || !strcmp($prescribe_name, ""))
			{
				continue;
			}

			$prescribe_value = (string)$objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();
			$prescribe_usemethod = (string)$objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();
			
			$data = array(
				'name' => $prescribe_name,
				'value' => $prescribe_value,
				'usemethod' => $prescribe_usemethod,
				);

			$querystring = $this->db->insert_string($prescribetable, $data);

			if (!$this->db->query($querystring))
			{
				$url = base_url().'index.php/zy_caselist/index/0';
				echo "导入处方失败！<a href=$url>回到病例汇总</a>";
				return;
			}
		}
		
		$url = base_url().'index.php/zy_caselist/index/0';
		echo "导入处方成功！<a href=$url>回到病例汇总</a>";
	}
	
	function importprescribedone()
	{
		$this->load->database();

		$uploadDir = $this->load->get_var('uploaddir');
		
		if (!file_exists ($uploadDir))
		{
			if (!mkdir($uploadDir))
			{
				$url = base_url().'index.php/zy_caselist/index/0';
				echo "导入处方失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
				return;
			}
		}

		$filename = "";
		$txtflag = 1;

		$tmpfile = $_FILES["prescribe_file"]['tmp_name'];

		if (!is_uploaded_file($tmpfile))
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "导入处方失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
			return;
		}
		
		$org_name = $_FILES["prescribe_file"]['name'];

		if (preg_match("/txt$/i", $org_name))
		{
			$filename = $uploadDir."/fangzi.txt";
		}
		else if (preg_match("/xls$/i", $org_name))
		{
			$filename = $uploadDir."/fangzi.xls";
			$txtflag = 0;
		}
		else
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "导入处方失败: 只支持TXT和EXCEL两种格式！<a href=$url>回到病例汇总</a>";
			return;
		}

		if (!move_uploaded_file($tmpfile, iconv("utf-8","gb2312",$filename)))
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "导入处方失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
			return;
		}
		
		if (!file_exists($filename))
		{
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "导入处方失败: 上传文件失败！<a href=$url>回到病例汇总</a>";
			return;
		}

		if ($txtflag)
		{
			error_reporting(0);
			$encoding = $this->get_encode($filename);
			error_reporting(E_ALL);
	
			if (strcmp($encoding, 'UTF-8') && strcmp($encoding, 'GB2312') && strcmp($encoding, 'ASCII'))
			{
				$url = base_url().'index.php/zy_caselist/index/0';
				echo "导入处方失败: 请使用UTF-8/GB2312/ASCII任意一种编码方式！<a href=$url>回到病例汇总</a>";
				return;
			}

			if ($this->importprescribe_todb($filename, $encoding) < 0)
			{
				$url = base_url().'index.php/zy_caselist/index/0';
				echo "有些处方导入失败，请自行检查！<a href=$url>回到病例汇总</a>";
				return;
			}
			
			$url = base_url().'index.php/zy_caselist/index/0';
			echo "导入处方成功！<a href=$url>回到病例汇总</a>";
		}
		else
		{
			$this->importexceldone($filename);
		}
	}

	function exportprescribe()
	{
		header("Content-type:text/html;charset=utf-8");

		$this->load->database();
		
		$prescribetable = $this->load->get_var('prescribetable');
		
		$querystring = "select * from $prescribetable";

		$query = $this->db->query($querystring);
 
		if(!$query)
		{
			return;
		}

		// Starting the PHPExcel library
		$this->load->library('PHPExcel');
		//$this->load->library('PHPExcel/IOFactory');

		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
		
		$objPHPExcel->setActiveSheetIndex(0);
		
		//PHPExcel_Calculation::getInstance()->cyclicFormulaCount = 1;
		
		// Field names in the first row
		$fields = $query->list_fields();
		
		/*
		$col = 0;
		foreach ($fields as $field)
		{
		   $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
		   $col++;
		}
		*/
		
		// Fetching the table data
		$row = 1;
		foreach($query->result() as $data)
		{
		   $col = 0;
		   foreach ($fields as $field)
		   {
		       $value = $data->$field;
		       $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($col, $row, $value, PHPExcel_Cell_DataType::TYPE_STRING);
		       $col++;
		   }
		
		   $row++;
		}
		
		$objPHPExcel->setActiveSheetIndex(0);
		
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		
		// Sending headers to force the user to download the file
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="处方_'.date('dMy').'.xls"');
		header('Cache-Control: max-age=0');
		
		$objWriter->save('php://output');
	}
	
	function exportprescribetxt()
	{
		$this->load->database();
		
    header("Content-Type: application/force-download"); //强制下载保存
    header("Content-Disposition:attachment;filename=处方.txt");
     
		$prescribetable = $this->load->get_var('prescribetable');

		$querystring = "select * from $prescribetable";

		$query = $this->db->query($querystring);
		$num = $query->num_rows();

		if (!$query)
		{
			echo "查询病例失败！";
			return;
		}
		
		foreach($query->result() as $row)
		{
			echo iconv('UTF-8', 'GB2312', $row->name)." ".iconv('UTF-8', 'GB2312', $row->value);
			echo "\r\n";
		}
	}
}

?>